import React,{useState,useEffect} from 'react'
/// 显示离线任务结果 2022-4-7

import DialogSimple from './DialogSimple' ;
import Button from 'react-bootstrap/Button';
import './DialogSimpleOfftaskResult.css' ;

import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend,
  } from 'chart.js';
  import {Line} from 'react-chartjs-2';


ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);

//const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];

// export const data = {
//   labels,
//   datasets: [
//     {
//       label: 'Dataset 1',
//       data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
//       borderColor: 'rgb(255, 99, 132)',
//       backgroundColor: 'rgba(255, 99, 132, 0.5)',
//     },
//     {
//       label: 'Dataset 2',
//       data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
//       borderColor: 'rgb(53, 162, 235)',
//       backgroundColor: 'rgba(53, 162, 235, 0.5)',
//     },
//   ],
// };


export const OfftaskResult_lineChart_options1 = {
    responsive: true,
    plugins: {
        legend: {
        position: 'top' ,
        },
        title: {
        display: true,
        text: '区域均值序列',
        },
    },
};
export const OfftaskResult_lineChart_options2 = {
    responsive: true,
    plugins: {
        legend: {
        position: 'top' ,
        },
        title: {
        display: true,
        text: '有效面积序列',
        },
    },
};

/// props.offtask
/// props.isOpen
/// props.onOk
/// props.onCancel
/// props.onAddLayer
function DialogSimpleOfftaskResult(props) {

    const [titleStr, setTitleStr] = useState('未知任务结果') ;
    const [showTextArea, setShowTextArea] = useState(true) ;
    const [textAreaContent, setTextAreaContent] = useState('') ;
    const [showLineChart, setShowLineChart] = useState(false) ;
    const [lineChartData1, setLineChartData1] = useState(null) ;
    const [lineChartData2, setLineChartData2] = useState(null) ;
    const [lineChartLabels, setLineChartLabels] = useState(null) ;
    const [showDownloadLink, setShowDownloadLink] = useState(false) ;
    const [showHtmlContent, setShowHtmlContent] = useState(false);
    const [downloadLink, setDownloadLink] = useState('') ;
    const [showAddLayer, setShowAddLayer] = useState(false) ;
    const [isAddLayerBusy, setIsAddLayerBusy] = useState(false) ;
    const [composeMypid, setComposeMypid] = useState(0) ;
    const [detailHtmlText, setDetailHtmlText] = useState("");


    const onAddLayer = function(){
        // 这里构造一个 lyrParams dpid 使用 mypid_hpid的负值，
        // 这样就可以避免与display表中的产品冲突，也可以唯一化这些用户临时合成产品
        setIsAddLayerBusy(true) ;
        let url = global.g_serverAPIRoot + 'product/info?pid=' + composeMypid;
        fetch(url).then(res=>res.json() )
        .then(result=>{
            setIsAddLayerBusy(false) ;
            let lyrParams = result.data ;
            lyrParams.displayid = "ud" + lyrParams.pid ;
            lyrParams.productDisplay.dpid = lyrParams.displayid ;
            lyrParams.productDisplay.pid= lyrParams.pid ;
            lyrParams.productDisplay.type='ud' ;
            lyrParams.productDisplay.productname=lyrParams.name ;
            lyrParams.productDisplay.params = {} ;
            props.onAddLayer(lyrParams) ;// here here here here
        })
        .catch(err=>{
            setIsAddLayerBusy(false) ;
        }) ;
    }


    useEffect(() => {
        if( props.offtask!== null )
        {
            if( props.offtask.mode===0 ) setTitleStr("区域统计结果") ;
            else if( props.offtask.mode===1 ) setTitleStr("序列分析结果") ;
            else if( props.offtask.mode===2 ) setTitleStr("序列分析结果") ;
            else if( props.offtask.mode===4 ) setTitleStr("数据合成结果") ;
            else if( props.offtask.mode===5 ) setTitleStr("数据导出结果") ;
            else if( props.offtask.mode===6 ) setTitleStr("通用离线任务结果") ;

            const resultjsonurl = global.g_staticResourceRoot+ props.offtask.resultfile;
            fetch(resultjsonurl)
            .then(response=>response.json())
            .then(result => {
                console.log(result) ;

                setTextAreaContent('') ;
                if( result.state!==0 )
                {
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);
                    
                    setShowTextArea(true) ;
                    setTextAreaContent("错误信息:"+result.message) ;
                }
                else if( props.offtask.mode===0 )
                {//序列分析
                    
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);


                    setShowTextArea(true) ;

                    const nband = result.data.length ;
                    let content = '' ;
                    for(let i = 0 ; i<nband; ++ i){
                        let mean = -999 ;
                        let stddev = -999 ;
                        if( result.data[i].validCnt>0 ) {
                            mean=result.data[i].sum/result.data[i].validCnt;
                            let variance = result.data[i].sq_sum/result.data[i].validCnt - mean*mean;
                            stddev = Math.sqrt(variance) ;
                        }
                        content += "波段" + (i+1) 
                        +"\n区域像元总数:"+result.data[i].allCnt
                        +"\n填充像元数:"+result.data[i].fillCnt
                        +"\n有效像元数:"+result.data[i].validCnt
                        +"\n像元值求和:"+result.data[i].sum
                        +"\n像元值平方和:"+result.data[i].sq_sum
                        +"\n有效最小值:"+result.data[i].validMin
                        +"\n有效最大值:"+result.data[i].validMax
                        +"\n有效面积(平方公里):"+result.data[i].areakm2
                        +"\n有效平均值:"+mean
                        +"\n有效标准差:"+stddev
                        ;
                    }
                    setTextAreaContent(content) ;
                }
                else if( props.offtask.mode===1 || props.offtask.mode===2 )
                {
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);
                    
                    const dataarr = result.data ;
                    let labels = [] ;
                    
                    let data1 = {} ;
                    let data2 = {} ;
                    for(let idata = 0 ; idata < dataarr.length; ++ idata)
                    {
                        labels.push( dataarr[idata].key ) ;
                    }
                    let nband = dataarr[0].data.length ;
                    data1.labels = labels ;
                    data2.labels = labels ;
                    data1.datasets = [] ;
                    data2.datasets = [] ;

                    for(let iband = 0 ; iband<nband ;++iband)
                    {
                        data1.datasets.push({label:'Band'+(iband+1), data:[]}) ;
                        data2.datasets.push({label:'Band'+(iband+1), data:[]}) ;

                        for(let idata = 0 ; idata<dataarr.length;++idata)
                        {
                            let meanval = 0 ;
                            if( dataarr[idata].data[iband].validCnt>0 ){
                                meanval = dataarr[idata].data[iband].sum/dataarr[idata].data[iband].validCnt;
                            }

                            data1.datasets[iband].data.push(meanval) ;
                            data2.datasets[iband].data.push(dataarr[idata].data[iband].areakm2) ;
                        }
                    }

                    setLineChartLabels(labels) ;
                    setLineChartData1(data1) ;
                    setLineChartData2(data2) ;
                    setShowLineChart(true) ;

                    let dlink = global.g_staticResourceRoot + props.offtask.resultfile + ".csv";
                    setDownloadLink(dlink) ;
                    setShowDownloadLink(true) ;

                }else if( props.offtask.mode===4 )
                {
                    //数据合成  显示到图层列表中
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);
                    
                    setShowAddLayer(true) ;
                    setIsAddLayerBusy(false) ;
                    setComposeMypid( result.mypid ) ;


                }else if( props.offtask.mode===5 )
                {
                    //数据导出
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);

					//here here here 2023-12-01
                    setShowDownloadLink(true) ;
                    let dlink = global.g_staticResourceRoot + props.offtask.resultfile.replace('-result.json','-result.tif');
                    setDownloadLink(dlink) ;

                }
                else if( props.offtask.mode===6 )
                {
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);

                    setShowHtmlContent(true);
                    setDetailHtmlText(result.data);
                }
                else{
                    //unknown mode
                    setShowTextArea(false) ;
                    setShowLineChart(false) ;
                    setShowDownloadLink(false) ;
                    setShowAddLayer(false) ;
                    setShowHtmlContent(false);

                    setShowTextArea(true) ;
                    setTextAreaContent("不支持的任务结果:"+props.offtask.mode) ;

                }
            
            }).catch(err=> {
                setShowTextArea(true) ;
                setShowLineChart(false) ;
                setShowDownloadLink(false) ;
                setShowAddLayer(false) ;
                setIsAddLayerBusy(false) ;
                setTextAreaContent("获取结果JSON文件失败，结果可能没有生成，请稍后重试.") ;
            }); ; 
    
        }
        
    }, [props.offtask])
    


    const renderContent = function () 
    {
        return (
            <div>
                {
                    (showTextArea)?
                    <textarea rows='20' className='ot-textarea' value={textAreaContent}></textarea>:""
                }
                {
                    (showDownloadLink)?
                    <Button size="sm"  target="_blank" href={downloadLink} >下载结果文件</Button>:""
                }
                {
                    (showLineChart)?
                    (
                        <>
                        <Line options={OfftaskResult_lineChart_options1} data={lineChartData1} />
                        <Line options={OfftaskResult_lineChart_options2} data={lineChartData2} />
                        </>
                    )
                    :""
                } 
                {
                    (showAddLayer)?
                    <Button size="sm" onClick={onAddLayer}
                    loading={isAddLayerBusy}
                    >在地图中显示</Button>:""
                }
                {
                    (showHtmlContent)?<div dangerouslySetInnerHTML={{ __html: detailHtmlText }}></div>:null
                }

            </div>
        )
    }

  return (
    <DialogSimple 
        isOpen={props.isOpen} 
        onCancel={props.onCancel} 
        dialogTitle={titleStr} 
        onOk={props.onOk} 
        renderContent={renderContent} />
  )
}

export default DialogSimpleOfftaskResult